//import JSEncrypt from 'jsencrypt/bin/jsencrypt';
const  JSEncrypt =   require('@/libs/encrypt/index')
import application from '@/settings/Application'

import CryptoJS from 'crypto-js'


const encryptor = new JSEncrypt.JSEncrypt() // 新建JSEncrypt对象
encryptor.setPublicKey(application.publicKey) // 设置公钥

export function AESEncrypt(word, keyStr){
    keyStr = keyStr ? keyStr : application.publicKey;
    var key  = CryptoJS.enc.Utf8.parse(CryptoJS.enc.Base64.parse(keyStr));//Latin1 Btr7w1tpsUf1B/C7Cin+Rw==
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {  mode:CryptoJS.mode.ECB,
      padding:CryptoJS.pad.NoPadding});
   //var encrypted = CryptoJS.SHA1(srcs, key)
    const s =  encrypted.ciphertext.toString(CryptoJS.enc.Base64)
    console.log('s:',s)
    return s;
    //return encrypted.toString();
}


export function encrypt(writeWords){
    return encryptor.encrypt(writeWords)
}

//inputTime 参数是毫秒级时间戳
export function formatDate() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
}

export function formatDate2(date1) {
	const date = new Date(Date.parse(date1.replace(/-/g, '/')))
	console.log('date:',date)
	console.log('y:',date.getFullYear())
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute;
}

//获取当前时间，格式YYYY-MM-DD
export function getNowFormatDate(seperator1='-') {
  var date = new Date();
 // var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('/')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

//判断字符是否为空的方法
export function isEmpty(obj){
  //typeof
  if(typeof obj == "undefined" || obj == null || obj == "" ){
    return true;
  }
  else if(typeof obj == 'object' && Object.keys(obj).length==0 ){
    return true;
  }else if(typeof obj == 'array' && obj.length == 0){
	  return true;
  }else{
    return false;
  }
}

export function isNotEmptyAndFunc(obj,callback) {
    if (!isEmpty(obj)){
        callback();
    }
}

export  function isPromise(obj) {

    return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';

}

// 检测所有的 state.js 并把 `initState()` 中的属性重置
export function resetState(mState) {
  if (mState.initState && typeof mState.initState === 'function') {
    const initState = mState.initState();
    for (const key in initState) {
      mState[key] = initState[key];
    }
  }
}
export function deepClone(obj){
  let _obj = JSON.stringify(obj),
    objClone = JSON.parse(_obj);
  return objClone
}

export function WxLogin() {
  return new Promise((resolve, reject) => {
    wx.login({
      success:res=>{
        let code = res.code;
        resolve(code);
      },
      fail:res=>{
        resolve(null);
      }
    });
  });
}

export function UniAsync(process) {
  return new Promise((resolve, reject) => {
      process(resolve)
  });
}
export function createURL (url,obj/*链接和参数*/){
  let params = [];
  Object.keys(obj).forEach((key, index)=>{
    //if (!isEmpty(obj[key])){
      params.push(key+"="+obj[key])
    //}
  });
  return url+'?'+params.reduce((s1,s2)=>s1+"&"+s2);
}


/* * 将对象转变为style字符串，对象属性的camel命名会转换为中划线命名 */
export function styles(obj) {
  let stylesStr = '';
  for (let styleName in obj)
  {
    if (obj.hasOwnProperty(styleName)) stylesStr += `${styleName.replace(/([A-Z])/g, "-$1").toLowerCase()}:${obj[styleName]};`;
  }
      return stylesStr;
}

export function Optional(val) {
  return isEmpty(val)?'':val;
}

export function rangeArray(start, end) {
  return Array(end - start + 1).fill(0).map((v, i) => i + start);
}

export function judgeExpireTimestamp(timestamp) {
    // const currentTime = new Date().getTime();
    // return  (currentTime - timestamp) > application.expireTime //7 * 24 * 3600 * 1000
    return false;
}

export function DeBounce(fn, delay=500){
    let timer;
    return function () {
        let args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
}

export function callbackSugar(callback,param){
  if (callback!=undefined && typeof callback == 'function'){
      callback(param);
  }
}

export function richContent(str){
  if(str=='' || str==undefined) return '';
  return  str.replace(/(\<img|\<p)/gi, function ($0, $1) {
          return {
            "<img": '<img style="max-width: 100%;height: auto;display:block;" ',
            "<p": '<p style="text-indent: 24px;" ',
            "<article":"<div",
            "</article": "</div",
            "<header": "<div",
            "</header": "</div"
          }[$1];
        });
}

export function showToast(message){
	uni.showToast({
		title:message,
		icon:'none',
		duration:2000
	})
}

//适配富文本中的图片,不超过屏幕宽度
export function adjustRichImg(richTxt){
	if(isEmpty(richTxt)){
		return '';
	}
	return richTxt.replace(/\<img/g,'<img style="max-width:100%;height:auto;"');
					
	
}